package com.aranandroid.customview.roundedcorner

import android.content.Context
import android.graphics.*
import android.graphics.drawable.ColorDrawable
import android.util.AttributeSet
import android.view.View
import android.view.ViewParent
import android.widget.FrameLayout


class RoundedCornerView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
    FrameLayout(context, attrs, defStyleAttr) {
    constructor(context: Context, attrs: AttributeSet?) : this(
        context,
        attrs,
        0
    )

    constructor(context: Context) : this(context, null) {

    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

    }


    private var maskBitmap: Bitmap? = null
    private var paint: Paint? = null
    private var maskPaint: Paint? = null
    var cornerRadius = 30f
        set(value) {
            field = value
            invalidate()
        }

    private fun init(context: Context, attrs: AttributeSet?, defStyle: Int) {
        val metrics = context.resources.displayMetrics
        paint = Paint(Paint.ANTI_ALIAS_FLAG)
        maskPaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
        maskPaint!!.setXfermode(PorterDuffXfermode(PorterDuff.Mode.CLEAR))
        setWillNotDraw(false)
    }

    override fun draw(canvas: Canvas) {
        // 根据原有背景颜色获取图片
        val offscreenBitmap =
            Bitmap.createBitmap(canvas.width, canvas.height, Bitmap.Config.ARGB_8888)
        val offscreenCanvas = Canvas(offscreenBitmap)
        super.draw(offscreenCanvas)
        // 画之前背景颜色
        canvas.drawBitmap(offscreenBitmap, 0f, 0f, paint)

        // 一个背景模板蒙上
        if (maskBitmap == null) {
            maskBitmap = createMask(canvas.width, canvas.height)
        }
        offscreenCanvas.drawBitmap(maskBitmap!!, 0f, 0f, maskPaint)
    }

    private fun createMask(width: Int, height: Int): Bitmap? {
        val mask = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(mask)
        val paint = Paint(Paint.ANTI_ALIAS_FLAG)
        var colorwhite = getParentColor(parent)

        paint.setColor(colorwhite)
        canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
        paint.setXfermode(PorterDuffXfermode(PorterDuff.Mode.CLEAR))
        canvas.drawRoundRect(
            RectF(0f, 0f, width.toFloat(), height.toFloat()),
            cornerRadius,
            cornerRadius,
            paint
        )
        return mask
    }

    /**
     * 获取父控件背景色
     */
    private fun getParentColor(parentme: ViewParent): Int {
        var colorwhite: Int = Color.WHITE
        if (parentme != null && (parentme as View).background != null) {
            colorwhite = ((parentme as View).background as ColorDrawable).color
        } else {
            if (parentme.parent != null) {
                colorwhite = getParentColor(parentme.parent)
            }
        }
        return colorwhite
    }

}